//
//  MineViewController.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/6/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "MineViewController.h"
#import "TopBackView.h"
#import "MineCell.h"
#import "InstallCell1.h"
#import "QiniuSDK.h"
#import "Common.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MineDetailVC.h"//用户详情
//#import "PerfectCarInfoVC1.h"//司机认证
//#import "MyWalletViewController.h"//钱包
#import "UseLineVC.h"//常跑路线
//#import "ClientCenterViewController.h"//客服中心
//#import "MyScoreViewController.h"//我的积分
#import "NewAboutViewController.h"
#import "RootViewController.h"
#import "WKProgressHUD.h"
#import "MissionViewController.h"
#import <SDWebImage/SDImageCache.h>
#import "PostPictureVC.h"
#import "UnusualOrderVC.h"//异常订单 事故订单
#import "MyDriverVC.h"//我的司机
#import "AppDelegate.h"

#import "OrderViewController.h"//我的运单


@interface MineViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) NSMutableArray *buttonArray;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NSMutableArray *imageArray;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) UIScrollView *scrollView;

//@property (nonatomic,strong) UIButton *xiaxianButton;

@property (nonatomic,strong) NSMutableDictionary *dataDictionary;


@property (nonatomic,copy) NSString *token;

@end

@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.dataDictionary = [NSMutableDictionary dictionary];

    self.buttonArray = [NSMutableArray arrayWithObjects:@"我的运单",@"异常回单",@"我的专线",@"我的司机",@"客服中心",nil];
    self.imageArray = [NSMutableArray arrayWithObjects:@"my_icon_list ",@"my_unusual",@"my_icon_line ",@"my_driver",@"my_icon_about", nil];
    
    
//    self.buttonArray = [NSMutableArray arrayWithObjects:@"我的运单",@"我的钱包",@"关于我们",nil];
//    self.imageArray = [NSMutableArray arrayWithObjects:@"my_icon_list ",@"my_personal_score",@"my_icon_about", nil];
////
    self.dataArray = [NSMutableArray array];
    
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"个人中心"];
    
    topBackView.leftButton.hidden = YES;
    topBackView.rightButton.hidden = YES;

    [self.view addSubview:topBackView];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;

    
//    self.view.backgroundColor = WhiteColor;
    [self initDataSource];
    [self initSubViews];
    
   
}

-(void)initSubViews
{
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    _scrollView.backgroundColor = GrayColor;
    [self.view addSubview:_scrollView];
    _scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 78*kHeight + self.buttonArray.count * cellHeight + 20) style:UITableViewStylePlain];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.backgroundColor = GrayColor;
    
    [_scrollView addSubview:self.tableView];
    
//    self.xiaxianButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.xiaxianButton.frame = CGRectMake(0, CGRectGetMaxY(self.tableView.frame)  , screenWidth , cellHeight);
//    [_scrollView addSubview:self.xiaxianButton];

    
    //下线按钮
//    [self initButton];
}

-(void)initButton
{
    UIButton *kefuButton = [UIButton buttonWithType:UIButtonTypeCustom];
    kefuButton.frame = CGRectMake(0, CGRectGetMaxY(self.tableView.frame)  , screenWidth , cellHeight);
//    NSString *string = [NSString stringWithFormat:@"客服电话:%@",phoneNumber];
    [kefuButton setTitle:@"下线"  forState:UIControlStateNormal];
    kefuButton.backgroundColor = WhiteColor;
    kefuButton.tag = 600;
    [kefuButton setTitleColor:YellowColor forState:UIControlStateNormal];
    [kefuButton addTarget:self action:@selector(xiaxianButton) forControlEvents:UIControlEventTouchUpInside];
//    kefuButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    kefuButton.titleEdgeInsets = UIEdgeInsetsMake(0, 18, 0, 0);
    kefuButton.titleLabel.font = Font(14);
    
    [_scrollView addSubview:kefuButton];

}

-(void)xiaxianButton
{
    NSString *string = [NSString stringWithFormat:@"%@user/modifyuserstatus?status=20",Main_interface];
    
    [Common requestWithUrlString:string contentType:application_json finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue]) {
           
            [WKProgressHUD popMessage:@"下线成功" inView:self.view duration:1.5 animated:YES];
            UIButton *button = (UIButton *)[self.view viewWithTag:600];
            [button setTitle:@"已下线" forState:UIControlStateNormal];
            [button setTitleColor:fontGrayColor forState:UIControlStateNormal];
            button.userInteractionEnabled = NO;
  
        } else {
            [WKProgressHUD popMessage:@"下线失败" inView:self.view duration:1.5 animated:YES];

        }
        
    } failed:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
    }];

    
}


-(void)initDataSource
{
    [Common requestWithUrlString:user_info contentType:application_json finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue]) {
            
            self.dataDictionary = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
            //赋值
            [self getValueString];
        } else {
            [WKProgressHUD popMessage:responseObj[@"message"] inView:self.view duration:1.5 animated:YES];

        }
        
    } failed:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
    }];

}

#pragma mark 赋值方法

-(void)getValueString
{
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    MineCell *cell = [self.tableView cellForRowAtIndexPath:index];
    
    NSString *string = [NSString stringWithFormat:@"%@",self.dataDictionary[@"driverStatus"]];
    if ([string isEqualToString:@"0"]) {
        
        cell.nameLabel.text = @"未认证";
        cell.nameLabel.textColor = littleBlackColor;
        cell.nameLabel.layer.borderColor = littleBlackColor.CGColor;
        cell.nameLabel.layer.borderWidth = 0.5;
    }
    
    if ([string isEqualToString:@"10"]) {
        
        cell.nameLabel.text = @"认证中";
        cell.nameLabel.textColor = Color_RGB(38, 206, 121, 1);
        cell.nameLabel.layer.borderColor = Color_RGB(38, 206, 121, 1).CGColor;
        cell.nameLabel.layer.borderWidth = 0.5;

    }

    if ([string isEqualToString:@"20"]) {
        
        cell.nameLabel.text = @"认证未通过";
        cell.nameLabel.textColor = Color_RGB(154, 154, 154, 1);
        cell.nameLabel.layer.borderColor = Color_RGB(154, 154, 154, 1).CGColor;
        cell.nameLabel.layer.borderWidth = 0.5;
        
    }

    if ([string isEqualToString:@"30"]) {
        
        cell.nameLabel.text = @"已认证";
        cell.nameLabel.textColor = Color_RGB(235, 130, 19, 1);
        cell.nameLabel.layer.borderColor = Color_RGB(235, 130, 19, 1).CGColor;
        cell.nameLabel.layer.borderWidth = 0.5;
        
    }
    
    [cell.nameLabel sizeToFit];
    cell.nameLabel.frame = CGRectMake(cell.nameLabel.frame.origin.x, cell.nameLabel.frame.origin.y, cell.nameLabel.frame.size.width + 5, 13 * kHeight);
    
//    cell.levelLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"levelName"]];
    
    cell.phoneLabel.text = [NSString stringWithFormat:@"%@",self.dataDictionary[@"phone"]];
    
    //修改支付密码使用
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:cell.phoneLabel.text forKey:@"phone"];
    
    
    if ([self.dataDictionary[@"pic"] isEqual:[NSNull null]]) {
        cell.ImageView.image = [UIImage imageNamed:@"home_portrait "];
    } else {
        
        //拼接图片url
        NSString *urlString = [NSString stringWithFormat:@"%@",self.dataDictionary[@"pic"]];
        
        [cell.ImageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"home_portrait "]];
        
        
    }

}

-(NSString *)backString:(NSString *)string
{
    
    if ([string isEqual:[NSNull null]]) {
        return @"";
    } else {
        return string;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
        
        return self.buttonArray.count;

    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        NSString *valueString = [userDefaults objectForKey:@"login"];
        if (valueString == nil) {
            //未登录
            
            NSString *string = @"installFirstCell1";
            InstallCell1 *cell = [tableView dequeueReusableCellWithIdentifier:string];
            if (!cell) {
                cell = [[InstallCell1 alloc]initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:string];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.pictureButton addTarget:self action:@selector(tapSelectPicture) forControlEvents:UIControlEventTouchUpInside];
            
            cell.pictureImageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50 * kWidth, 50 * kHeight)];
            cell.pictureImageV.layer.cornerRadius = 25 * kWidth;
            cell.pictureImageV.layer.masksToBounds = YES;
            cell.pictureImageV.image = [UIImage imageNamed:@"home_portrait "];
            [cell.pictureButton addSubview:cell.pictureImageV];
            
            return cell;
            
        } else {
       
        NSString *cellString = @"mineCell";
        MineCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell = [[MineCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellString];
        }
        
        cell.ImageView.image = [UIImage imageNamed:@"home_portrait "];
            
            //不让上传图片！！

//        cell.ImageView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapSelectPicture)];
        [cell.ImageView addGestureRecognizer:tap];
        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"personal_arrow"]];

                return cell;
            
        
        }
        
    } else {

    NSString *cellString = @"mineCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
    }
    
        cell.textLabel.text = self.buttonArray[indexPath.row];

        cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"personal_arrow"]];

        cell.textLabel.font = Font(13);
        cell.textLabel.textColor = littleBlackColor;
        cell.imageView.image = [UIImage imageNamed:self.imageArray[indexPath.row]
];
        
        
    return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return  78 * kWidth;
    } else {
        return  cellHeight;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        MineDetailVC *detailVC = [[MineDetailVC alloc]init];
        
        [Common isLogin:self andPush:detailVC];
        
//        [self.navigationController pushViewController:detailVC animated:YES];

    }
    
    
//    //车队认证
//    if (indexPath.row == 0 &&indexPath.section == 1) {
//        PerfectCarInfoVC1 *perfectVC1 = [[PerfectCarInfoVC1 alloc]init];
//        
//        [Common isLogin:self andPush:perfectVC1];
//    }
    
    //我的运单
    if (indexPath.row == 0 &&indexPath.section == 1) {
        OrderViewController *missionVC = [[OrderViewController alloc]init];
        missionVC.hide = @"1";
        [Common isLogin:self andPush:missionVC];
    }
//    异常回单
    if (indexPath.row == 1 &&indexPath.section == 1) {
       
        UnusualOrderVC *unusualVC = [[UnusualOrderVC alloc]init];
        unusualVC.titleString = @"异常回单";
        [Common isLogin:self andPush:unusualVC];

        
    }
    
//    //事故运单
//    if (indexPath.row == 3 &&indexPath.section == 1) {
//        UnusualOrderVC *unusualVC = [[UnusualOrderVC alloc]init];
//        unusualVC.titleString = @"事故运单";
//        [Common isLogin:self andPush:unusualVC];
//
//    }
    //我的线路
    if (indexPath.row == 2 &&indexPath.section == 1) {
       
        UseLineVC *lineVC = [[UseLineVC alloc]init];
        [Common isLogin:self andPush:lineVC];

    }
    
    //我的司机
    if (indexPath.row == 3 &&indexPath.section == 1) {
        MyDriverVC *driverVC = [[MyDriverVC alloc]init];
        
        [Common isLogin:self andPush:driverVC];

    }
    
    
    //客服中心
    if (indexPath.row == 4 &&indexPath.section == 1) {
        
        NewAboutViewController *aboutVC = [[NewAboutViewController alloc]init];
        
        [self.navigationController pushViewController:aboutVC animated:YES];
        
    }

    

}


-(void)clearCache:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}




-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]init];
    
    view.backgroundColor = GrayColor;
    
    return view;
}


//获取图片
-(void)tapSelectPicture
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf getPictureFromLibrary];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
        MineCell *cell = [self.tableView cellForRowAtIndexPath:index];
        
        cell.ImageView.image = image;
        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}


-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 0.5);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    
    [Common requestWithUrlString:picture_qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            
            self.token = responseObj[@"data"];
            
            NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
            MineCell *cell = [self.tableView cellForRowAtIndexPath:index];
            
            [self uploadImageToQNWithData:[self getImageWith:cell.ImageView.image
]];
        }
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
    
    
}

-(void)uploadImageToQNWithData:(NSData *)data
{

    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        
        [self changePhotoWithString:resp[@"key"]];
        
        
    } option:uploadOption];
}

//调用更换头像接口
-(void)changePhotoWithString:(NSString *)string
{
//
    NSString *brithday ;
    if ([self.dataDictionary[@"birthday"] isEqual:[NSNull null]]) {
        brithday = @"";
    } else {
        brithday = [NSString stringWithFormat:@"%@",self.dataDictionary[@"birthday"]];
    }
    
    
    NSDictionary *dictionary =
    @{@"pic":string,
      @"pwd":[NSString stringWithFormat:@"%@", self.dataDictionary[@"pwd"]],
      @"name":[NSString stringWithFormat:@"%@",self.dataDictionary[@"realName"]],
      @"email":[NSString stringWithFormat:@"%@",self.dataDictionary[@"email"]],
      @"gender":[NSString stringWithFormat:@"%@",self.dataDictionary[@"gender"]],
      @"birthday":brithday,
      };
    
    
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:user_modify parms:dictionary finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"%@",dic);
        
    } failedBlock:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
        
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:NO];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"dismiss" object:nil];
    
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    
//    NSString *valueString = [userDefaults objectForKey:@"login"];
//    if (valueString == nil) {
//        
        //重新刷新section
        NSIndexSet *index = [[NSIndexSet alloc]initWithIndex:0];
        
        [self.tableView reloadSections:index withRowAnimation:UITableViewRowAnimationNone];
    
//    }
    
    //修改信息后 重新请求数据
    [self initDataSource];
    
    [self checkOnline];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;

}

//查询用户信息
-(void)checkOnline
{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *valueString = [userDefaults objectForKey:@"login"];
    if (valueString == nil) {
        
        UIButton *button = (UIButton *)[self.view viewWithTag:600];
        button.hidden = YES;
        
        
    } else {
        
        
        UIButton *button = (UIButton *)[self.view viewWithTag:600];
        button.hidden = NO;
  
        
    [Common requestWithUrlString:user_info contentType:application_json finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue]) {
            
            
            UIButton *button = (UIButton *)[self.view viewWithTag:600];

            NSString *valueString = [NSString stringWithFormat:@"%@",responseObj[@"data"][@"userStatus"]];
            
            if ( [valueString isEqualToString:@"10"]) {
                
                [button setTitle:@"下线" forState:UIControlStateNormal];
                [button setTitleColor:YellowColor forState:UIControlStateNormal];
                button.userInteractionEnabled = YES;
                
            } else {
                [button setTitle:@"已下线" forState:UIControlStateNormal];
                [button setTitleColor:fontGrayColor forState:UIControlStateNormal];
                button.userInteractionEnabled = NO;
                
            }
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
        
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
